package com.ciwong.epaper.modules.epaper.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.bookstore.bean.PublishWorkContent;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakChildren;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakExAminAtion;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakExaminBean;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakParts;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ResourceContent;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.MyWebViewClient;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:听说模考选题页面
 * @author: wyk
 * @time: 2021/6/18 15:20
 */
public class ListenSpeakChooseWorkHtml extends BaseHtmlActicity {

    private ImageView choose_work_go_back;
    //全选按钮
    private CheckBox listen_speak_choose_work;


    private TextView listen_speak_choose_detail_text;

    private String versionId, contentId;
    //资源url
    private String resourceUrl;
    //资源名
    private String resourceName;
    //是否选中
    private Boolean isChecked;

    //父目录versionId
    private String parentVersionId;

    private int moduleId;

    private String resourceType;

    private ListenSpeakExaminBean listenSpeakExaminBean = new ListenSpeakExaminBean();

    private ListenSpeakExAminAtion listenSpeakExAminAtion = new ListenSpeakExAminAtion();

    private String tag;
    //作业分数
    private float workScore;

    //大题数量
    private int examinCount;
    //总作业时长
    private double workLong;
    //选中的作业时长
    private double chooseListenSpeakWorkLong;

    private String workName;

    //资源内容
    private ResourceContent resourceContent;

    private TextView listen_speak_work_long_text;
    private TextView listen_zk_or_sq;

    private RelativeLayout choose_sentence_finish;
    private BridgeWebView bridgeWebView;
    //默认收起状态
    private int zkOrSq = 1;

    @Override
    protected int setView() {
        return R.layout.activity_listen_speak_html;
    }

    @Override
    protected void findViews() {
        choose_work_go_back = findViewById(R.id.choose_work_go_back);
        listen_speak_choose_work = findViewById(R.id.listen_speak_choose_work);
        listen_speak_choose_detail_text = findViewById(R.id.listen_speak_choose_detail_text);
        choose_sentence_finish = findViewById(R.id.choose_sentence_finish);
        listen_zk_or_sq = findViewById(R.id.listen_zk_or_sq);
        listen_speak_work_long_text = findViewById(R.id.listen_speak_work_long_text);
        bridgeWebView = findViewById(R.id.listen_speak_webview);
        listen_zk_or_sq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (zkOrSq == 1) {
                    listen_zk_or_sq.setText("展开");
                    zkOrSq = 0;
                    accordionQuestion(1);
                } else {
                    listen_zk_or_sq.setText("收起");
                    zkOrSq = 1;
                    accordionQuestion(0);
                }
            }
        });


        listen_speak_choose_work.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!compoundButton.isPressed()) {
                    return;
                }
                if (b) {
                    listen_speak_choose_work.setChecked(true);
                    listen_speak_choose_work.setSelected(true);
                    listenSpeakExaminBean.setCheckCount(examinCount);
                    List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
                    for (int i = 0; i < parts.size(); i++) {
                        parts.get(i).setChecked(true);
                    }
                    JSONObject allSelect = new JSONObject();
                    allSelect.put("allSelect", 1);
                    allSelect(allSelect.toJSONString());
                    //listenSpeakChooseWorkAdapter.notifyDataSetChanged();
                    setCheckStatus();
                } else {
                    listen_speak_choose_work.setChecked(false);
                    listen_speak_choose_work.setSelected(true);
                    listenSpeakExaminBean.setCheckCount(0);
                    List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
                    for (int i = 0; i < parts.size(); i++) {
                        parts.get(i).setChecked(false);
                    }
                    JSONObject allSelect = new JSONObject();
                    allSelect.put("allSelect", 0);
                    allSelect(allSelect.toJSONString());
                    setCheckStatus();
                    //listenSpeakChooseWorkAdapter.notifyDataSetChanged();
                }
            }
        });

        choose_sentence_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        choose_work_go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    protected void initEvent() {

    }


    @Override
    protected void init() {
        Intent intent = getIntent();
        versionId = intent.getStringExtra(IntentFlag.INTENT_FLAG_VERSION_ID);
        parentVersionId = intent.getStringExtra(IntentFlag.INTENT_FLAG_PARENT_VERSION_ID);
        resourceName = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME);
        workName = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME);
        setTitleText(resourceName);
        resourceName = toUtf8(resourceName);
        resourceUrl = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_URL);
        tag = intent.getStringExtra(IntentFlag.INTENT_FLAG_TAG);
        workLong = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_LONG, 0);
        moduleId = intent.getIntExtra(IntentFlag.INTENT_FLAG_MODULE_ID, 0);
        isChecked = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_BOOLEAN, false);
        resourceType = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_TYPE);
        listenSpeakExaminBean = (ListenSpeakExaminBean) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        if (null == listenSpeakExaminBean) {
            listenSpeakExaminBean = new ListenSpeakExaminBean();
        }

    }

    private void loadWeb() {
        JSONObject allSelect = new JSONObject();
        if (null != listenSpeakExaminBean) {
            int checkCount = listenSpeakExaminBean.getCheckCount();
            listenSpeakExAminAtion = listenSpeakExaminBean.getListenSpeakExAminAtion();
            if (checkCount == listenSpeakExAminAtion.getParts().size()) {
                allSelect.put("allSelect", 1);
            } else {
                allSelect.put("allSelect", 0);
            }
        }
        bridgeWebView.setDefaultHandler(new DefaultHandler());
        bridgeWebView.setWebChromeClient(new WebChromeClient());
        String url = getjumpURL();
        bridgeWebView.loadUrl(url);
        //设置webSettings，允许其加载混合网络协议内容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            bridgeWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        bridgeWebView.setWebViewClient(new MyWebViewClient(bridgeWebView));
        allSelect(allSelect.toJSONString());

        bridgeWebView.registerHandler("singleSelect", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (null != data && !"".equals(data)) {
                    JSONObject checkStatus = JSONObject.parseObject(data);
                    Boolean selected = checkStatus.getBooleanValue("selected");
                    List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
                    parts.get(checkStatus.getIntValue("index")).setChecked(selected);
                    if (selected) {
                        listenSpeakExaminBean.setCheckCount(listenSpeakExaminBean.getCheckCount() + 1);
                    } else {
                        listenSpeakExaminBean.setCheckCount(listenSpeakExaminBean.getCheckCount() - 1);
                    }
                    setCheckStatus();
                }
                //ToastUtil.INSTANCE.toastCenterError(data);
            }
        });

        bridgeWebView.registerHandler("getSelectArray", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //ToastUtil.INSTANCE.toastCenterError(data);
                String selectArray = getSelectArray();
                function.onCallBack(selectArray);
            }
        });
    }


    /**
     * 获取资源内容统计信息
     *
     * @param parentVersionId
     * @param versionId
     * @param moduleId
     * @param resourceType    资源类型
     */
    public void getResourceStatisticsWeb(String parentVersionId, final String versionId, int moduleId, final String resourceType) {

        EpaperDao.getInstance().getResourceStatisticsWeb(parentVersionId, versionId, moduleId, resourceType, new BaseExtCallBack(ListenSpeakChooseWorkHtml.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void success(Object data) {
                if (null != data) {
                    resourceContent = (ResourceContent) data;
                    workScore = resourceContent.getRefScore();
                    if (tag.equals(RequestCode.TeaWorkContent.LISTEN_SPRAK)) {
                        ListenSpeakExaminAtion(versionId);
                    } else {
                        examinationData(versionId);
                    }
                }
            }
        });
    }


    /**
     * 获取在线作答内容
     */
    public void examinationData(final String versionid) {
        EpaperDao.getInstance().examinationData(versionid, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    listenSpeakExAminAtion = (ListenSpeakExAminAtion) data;
                    if (!isChecked) {
                        listenSpeakExaminBean.setCheckCount(0);
                        for (int i = 0; i < listenSpeakExAminAtion.getParts().size(); i++) {
                            listenSpeakExAminAtion.getParts().get(i).setChecked(false);
                        }
                    } else {
                        //全选
                        listenSpeakExaminBean.setCheckCount(listenSpeakExAminAtion.getParts().size());
                        for (int i = 0; i < listenSpeakExAminAtion.getParts().size(); i++) {
                            listenSpeakExAminAtion.getParts().get(i).setChecked(true);
                        }
                    }
                    listenSpeakExaminBean.setListenSpeakExAminAtion(listenSpeakExAminAtion);
                    double sentenceTime;
                    int itemCount = 1;
                    if (0 == resourceContent.getRefAnswerTime()) {
                        sentenceTime = 0 == resourceContent.getDefAnswerTime() ? 60 : resourceContent.getDefAnswerTime();
                        if (resourceContent.getSmallQuesCount() > 0) {
                            itemCount = resourceContent.getSmallQuesCount();
                        } else if (resourceContent.getBigQuesCount() > 0) {
                            itemCount = resourceContent.getBigQuesCount();
                        } else if (resourceContent.getItemCount() > 0) {
                            itemCount = resourceContent.getItemCount();
                        }
                        workLong = (int) (Math.ceil(sentenceTime * itemCount));
                    } else {
                        workLong = resourceContent.getRefAnswerTime() * 60;
                    }
                    loadWeb();
                    setCheckStatus();
                }
            }
        });
    }

    /**
     * 获取听说模考内容
     */
    private void ListenSpeakExaminAtion(final String versionid) {
        EpaperDao.getInstance().ListenSpeakExaminAtion(versionid, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    listenSpeakExAminAtion = (ListenSpeakExAminAtion) data;
                    if (!isChecked) {
                        listenSpeakExaminBean.setCheckCount(0);
                        for (int i = 0; i < listenSpeakExAminAtion.getParts().size(); i++) {
                            listenSpeakExAminAtion.getParts().get(i).setChecked(false);
                        }

                    } else {
                        listenSpeakExaminBean.setCheckCount(listenSpeakExAminAtion.getParts().size());
                        for (int i = 0; i < listenSpeakExAminAtion.getParts().size(); i++) {
                            listenSpeakExAminAtion.getParts().get(i).setChecked(true);
                        }
                    }
                    listenSpeakExaminBean.setListenSpeakExAminAtion(listenSpeakExAminAtion);

                    double sentenceTime;
                    sentenceTime = 0 == resourceContent.getDefAnswerTime() ? 180 : resourceContent.getDefAnswerTime();
                    workLong = ((int) (Math.ceil(sentenceTime * resourceContent.getBigQuesCount())));
                    loadWeb();
                    setCheckStatus();
                }
            }
        });
    }

    public void allSelect(String allSelect) {
        bridgeWebView.callHandler("allSelect", allSelect, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                //ToastUtil.INSTANCE.toastCenterSuccess("传递选中状态");
            }
        });
    }

    //通知网页展开或收起
    public void accordionQuestion(int tag) {
        bridgeWebView.callHandler("accordionQuestion", tag + "", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
    }


    //返回h5所有选中的段落
    public String getSelectArray() {
        JSONObject selectJson = new JSONObject();
        List<Integer> selectArray = new ArrayList<>();
        if (null != listenSpeakExaminBean) {
            List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
            int checkCount = listenSpeakExaminBean.getCheckCount();
            if (checkCount == parts.size()) {
                for (int i = 0; i < parts.size(); i++) {
                    selectArray.add(i);
                }
            } else if (checkCount > 0) {
                for (int i = 0; i < parts.size(); i++) {
                    if (null == parts.get(i).getChecked() || parts.get(i).getChecked()) {
                        selectArray.add(i);
                    }
                }
            }
        }
        selectJson.put("selectArray", selectArray);
        return selectJson.toJSONString();
    }

    public static String toUtf8(String str) {
        String result = null;
        try {
            result = URLEncoder.encode(str, "UTF-8");
            result = result.replace("+", "%20");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置选择详情
     */
    public void setCheckStatus() {
        if (ModuleContent.ResourceType.RESOURCE_TYPE_ONLINE_ANSWER.equals(resourceType)) {
            //在线作答
            if (examinCount == listenSpeakExaminBean.getCheckCount()) {
                //全选
                chooseListenSpeakWorkLong = workLong / examinCount * listenSpeakExaminBean.getCheckCount();
                chooseListenSpeakWorkLong = Math.ceil(chooseListenSpeakWorkLong);
            } else if (0 == listenSpeakExaminBean.getCheckCount()) {
                //一个没选
                chooseListenSpeakWorkLong = workLong / examinCount * listenSpeakExaminBean.getCheckCount();
                chooseListenSpeakWorkLong = Math.ceil(chooseListenSpeakWorkLong);
            } else {
                double workCheckLong = 0;
                if (resourceContent != null && 0 == resourceContent.getRefAnswerTime()) {
                    workCheckLong = workLong / examinCount * listenSpeakExaminBean.getCheckCount();
                } else {
                    //选了一些
                    for (int i = 0; i < listenSpeakExAminAtion.getParts().size(); i++) {
                        if (listenSpeakExAminAtion.getParts().get(i).getChecked()) {
                            workCheckLong = workCheckLong + listenSpeakExAminAtion.getParts().get(i).getModule_anwser_time() * 60;
                        }
                    }
                }
                chooseListenSpeakWorkLong = Math.ceil(workCheckLong);
            }
        } else {
            //听说模考
            chooseListenSpeakWorkLong = workLong / examinCount * listenSpeakExaminBean.getCheckCount();
            chooseListenSpeakWorkLong = Math.ceil(chooseListenSpeakWorkLong);
        }
        int workRefLong = ((int) (Math.ceil(chooseListenSpeakWorkLong / 60)));
        SpannableStringBuilder chooseCountText = new SpannableStringBuilder("已选择 " + listenSpeakExaminBean.getCheckCount() + " 个大题");
        SpannableStringBuilder chooseWorkLongText = new SpannableStringBuilder("预计 " + (int) workRefLong + " 分钟");
        ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#5ce191"));

        if (listenSpeakExaminBean.getCheckCount() < 10) {
            chooseCountText.setSpan(GreenSpan, 4, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            chooseCountText.setSpan(GreenSpan, 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if (workRefLong >= 100) {
            chooseWorkLongText.setSpan(GreenSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else if (workRefLong < 10) {
            chooseWorkLongText.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            chooseWorkLongText.setSpan(GreenSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        listen_speak_choose_detail_text.setText(chooseCountText);
        listen_speak_work_long_text.setText(chooseWorkLongText);
        if (examinCount == listenSpeakExaminBean.getCheckCount()) {
            listen_speak_choose_work.setChecked(true);
            listen_speak_choose_work.setSelected(true);
        } else if (0 == listenSpeakExaminBean.getCheckCount()) {
            listen_speak_choose_work.setChecked(false);
            listen_speak_choose_work.setSelected(true);
        } else {
            listen_speak_choose_work.setChecked(true);
            listen_speak_choose_work.setSelected(false);
        }
        //listenSpeakChooseWorkAdapter.notifyDataSetChanged();
    }

    /**
     * 获取跳转详情的url
     *
     * @return
     */
    public String getjumpURL() {
        String url = "";
        if (tag.equals(RequestCode.TeaWorkContent.LISTEN_SPRAK)) {
            if (null != listenSpeakExaminBean && null != listenSpeakExaminBean.getListenSpeakExAminAtion()) {
                examinCount = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts().size();
                setCheckStatus();
                BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
                if (verifyInfo != null) {
                    String clientId = verifyInfo.getClientId();
                    String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
                    String brandId = EApplication.BRAND_ID + "";
                    bridgeWebView.setDefaultHandler(new DefaultHandler());
                    bridgeWebView.setWebChromeClient(new WebChromeClient());
                    url = EpaperConstant.URL_H5_LISTEN_SPEAK_BIG_QUESTION + "versionId=" + versionId +
                            "&clientId=" + clientId + "&userId=" + userId + "&brandId=" + brandId + "&resourceName=" + resourceName;
                }
                //listenSpeakChooseWorkAdapter.notifyDataSetChanged();
            }

        } else if (tag.equals(RequestCode.TeaWorkContent.ANSWER_ONLINE)) {
            if (null != listenSpeakExaminBean && null != listenSpeakExaminBean.getListenSpeakExAminAtion()) {
                examinCount = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts().size();
                setCheckStatus();
                BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
                if (verifyInfo != null) {
                    String clientId = verifyInfo.getClientId();
                    String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
                    String brandId = EApplication.BRAND_ID + "";
                    bridgeWebView.setDefaultHandler(new DefaultHandler());
                    bridgeWebView.setWebChromeClient(new WebChromeClient());
                    url = EpaperConstant.URL_H5_ONLINE_PAGE_BIG_QUESTION + "brandId=" + brandId +
                            "&clientId=" + clientId + "&versionId=" + versionId;
                }
                //listenSpeakChooseWorkAdapter.notifyDataSetChanged();
            }

        } else {
            hideCricleProgress();
            ToastUtil.INSTANCE.toastCenterError("加载失败，请稍后重试");
        }
        return url;
    }

    @Override
    protected void loadData() {
        /*if (null != listenSpeakExaminBean && null != listenSpeakExaminBean.getListenSpeakExAminAtion() && 0 != listenSpeakExaminBean.getCheckCount()) {
            examinCount = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts().size();
            setCheckStatus();
            //chooseSentenceAdapter.notifyDataSetChanged();
        } else {
            showCricleProgress();
            getResourceStatisticsWeb(parentVersionId,versionId,moduleId,resourceType);
        }*/
        if (isChecked && null != listenSpeakExaminBean && null != listenSpeakExaminBean.getListenSpeakExAminAtion()) {
            loadWeb();
        } else {
            showCricleProgress();
            getResourceStatisticsWeb(parentVersionId, versionId, moduleId, resourceType);
        }
    }

    @Override
    protected void onDestroy() {
        if (null != bridgeWebView) {
            bridgeWebView.destroy();
        }
        super.onDestroy();
    }

    /**
     * 获取在线作答内容
     */

    @Override
    public void finish() {
        setChooseWork();
        super.finish();
    }


/*    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            setChooseWork();
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }*/

    /**
     * 设置选择的作业 返回
     */
    public void setChooseWork() {
        StringBuffer str = new StringBuffer();
        workScore = 0;
        List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
        int checkCount = listenSpeakExaminBean.getCheckCount();
        for (int i = 0; i < parts.size(); i++) {
            if (parts.size() == checkCount) {
                if (null != parts.get(i).getChildren() && parts.get(i).getChildren().size() > 0) {
                    List<ListenSpeakChildren> children = parts.get(i).getChildren();
                    for (int i1 = 0; i1 < children.size(); i1++) {
                        if (null != children.get(i1).getChildren() && children.get(i1).getChildren().size() > 0) {
                            List<ListenSpeakChildren> childrens = children.get(i1).getChildren();
                            for (int i2 = 0; i2 < childrens.size(); i2++) {
                                workScore = workScore + childrens.get(i2).getQuestion_ref_sorce();
                            }
                        } else {
                            workScore = workScore + children.get(i1).getQuestion_ref_sorce();
                        }
                    }
                } else {
                    workScore = workScore + parts.get(i).getQuestion_ref_sorce();
                }
                if (str.length() == 0 || "".equals(str)) {
                    str.append(i);
                } else {
                    str.append("," + i);
                }
            } else {
                if (null != parts.get(i).getChildren() && parts.get(i).getChildren().size() > 0) {
                    if (null == parts.get(i).getChecked() || parts.get(i).getChecked()) {
                        List<ListenSpeakChildren> children = parts.get(i).getChildren();
                        for (int i1 = 0; i1 < children.size(); i1++) {
                            if (null != children.get(i1).getChildren() && children.get(i1).getChildren().size() > 0) {
                                List<ListenSpeakChildren> childrens = children.get(i1).getChildren();
                                for (int i2 = 0; i2 < childrens.size(); i2++) {
                                    workScore = workScore + childrens.get(i2).getQuestion_ref_sorce();
                                }
                            } else {
                                workScore = workScore + children.get(i1).getQuestion_ref_sorce();
                            }
                        }
                    }
                }
                if (null == parts.get(i).getChecked() || parts.get(i).getChecked()) {
                    if (str.length() == 0 || "".equals(str)) {
                        str.append(i);
                    } else {
                        str.append("," + i);
                    }
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        PublishWorkContent publishWorkContent = new PublishWorkContent();
        publishWorkContent.setCheckedResource(str.toString());
        publishWorkContent.setTotalQuesNum(listenSpeakExaminBean.getCheckCount());
        publishWorkContent.setRequirementContent(jsonObject.toString());
        publishWorkContent.setRefLong((int) chooseListenSpeakWorkLong);
        publishWorkContent.setTotalWorkLong((int) workLong);
        publishWorkContent.setListenSpeakExaminBean(listenSpeakExaminBean);
        publishWorkContent.setModuleId(moduleId);
        publishWorkContent.setParentVersionId(parentVersionId);
        publishWorkContent.setVersionId(versionId);
        publishWorkContent.setWorkScore(workScore);
        publishWorkContent.setResourceName(workName);
        publishWorkContent.setResourceType(resourceType);
        publishWorkContent.setResourceUrl(resourceUrl);
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_WORD_DETAILS, str.toString());
        intent.putExtra(IntentFlag.INTENT_FLAG_RESOURCE_URL, resourceUrl);
        intent.putExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME, workName);
        intent.putExtra(IntentFlag.INTENT_FLAG_VERSION_ID, versionId);
        intent.putExtra(IntentFlag.INTENT_FLAG_JSONOBJECT, jsonObject.toString());
        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_LONG, (int) chooseListenSpeakWorkLong);
        intent.putExtra(IntentFlag.INTENT_FLAG_OBJ, listenSpeakExaminBean);
        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_SCORE, workScore);
        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_CONTENT, publishWorkContent);
        setResult(RESULT_OK, intent);
    }
}
